import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import pandas as pd
import json

import os

class CSVDataProcessor:
    def __init__(self, root):
        self.root = root
        self.root.title("CSV数据处理工具")
        self.root.geometry("900x600")
        self.root.minsize(800, 500)
        
    
        
        # 数据变量
        self.input_file_path = tk.StringVar()
        self.output_file_path = tk.StringVar()
        self.header_row = tk.IntVar(value=36)
        self.data_start_row = tk.IntVar(value=40)
        self.processed_data = None
        self.column_headers = []
        
        # 创建界面
        self.create_widgets()
        
    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 顶部框架 - 文件选择和设置
        top_frame = ttk.LabelFrame(main_frame, text="文件设置", padding="10")
        top_frame.pack(fill=tk.X, pady=5)
        
        # 输入文件选择
        ttk.Label(top_frame, text="输入CSV文件:").grid(row=0, column=0, sticky=tk.W, pady=5)
        ttk.Entry(top_frame, textvariable=self.input_file_path, width=60).grid(row=0, column=1, padx=5, pady=5)
        ttk.Button(top_frame, text="浏览...", command=self.browse_input_file).grid(row=0, column=2, padx=5, pady=5)
        
        # 输出文件选择
        ttk.Label(top_frame, text="输出JSON文件:").grid(row=1, column=0, sticky=tk.W, pady=5)
        ttk.Entry(top_frame, textvariable=self.output_file_path, width=60).grid(row=1, column=1, padx=5, pady=5)
        ttk.Button(top_frame, text="浏览...", command=self.browse_output_file).grid(row=1, column=2, padx=5, pady=5)
        
        # 行设置
        row_frame = ttk.Frame(top_frame)
        row_frame.grid(row=2, column=0, columnspan=3, sticky=tk.W, pady=5)
        
        ttk.Label(row_frame, text="表头行号:").pack(side=tk.LEFT, padx=5)
        ttk.Entry(row_frame, textvariable=self.header_row, width=5).pack(side=tk.LEFT, padx=5)
        
        ttk.Label(row_frame, text="数据起始行号:").pack(side=tk.LEFT, padx=5)
        ttk.Entry(row_frame, textvariable=self.data_start_row, width=5).pack(side=tk.LEFT, padx=5)
        
        # 处理按钮
        ttk.Button(top_frame, text="开始处理", command=self.process_data).grid(row=2, column=2, sticky=tk.E, padx=5, pady=5)
        
        # 中间框架 - 日志显示
        log_frame = ttk.LabelFrame(main_frame, text="处理日志", padding="10")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.log_text = tk.Text(log_frame, wrap=tk.WORD, height=10)
        self.log_text.pack(fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(self.log_text, command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.config(yscrollcommand=scrollbar.set)
        
        
    def browse_input_file(self):
        filename = filedialog.askopenfilename(
            title="选择CSV文件",
            filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
        )
        if filename:
            self.input_file_path.set(filename)
            # 自动生成输出文件名
            base_name = os.path.basename(filename)
            output_name = os.path.splitext(base_name)[0] + ".json"
            output_dir = os.path.dirname(filename)
            self.output_file_path.set(os.path.join(output_dir, output_name))
    
    def browse_output_file(self):
        filename = filedialog.asksaveasfilename(
            title="保存JSON文件",
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        if filename:
            self.output_file_path.set(filename)
    
    def log_message(self, message):
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
    
    def process_data(self):
        # 清空日志和表格
        self.log_text.delete(1.0, tk.END)

        
        input_file = self.input_file_path.get()
        output_file = self.output_file_path.get()
        
        if not input_file:
            messagebox.showerror("错误", "请选择输入CSV文件")
            return
        
        if not output_file:
            messagebox.showerror("错误", "请选择输出JSON文件")
            return
        
        try:
            self.log_message(f"开始处理文件: {input_file}")
            
            # 读取CSV文件
            df = pd.read_csv(input_file, sep='\t', header=None)
            self.log_message(f"已读取文件，共 {len(df)} 行")
            
            # 提取列标题
            header_row = self.header_row.get() - 1  # 转换为0-based索引
            if header_row < 0 or header_row >= len(df):
                messagebox.showerror("错误", f"表头行号超出范围 (有效范围: 1-{len(df)})")
                return
                
            column_headers = str(df.iloc[header_row, 0]).split(',')
            self.column_headers = column_headers
            self.log_message(f"已提取表头 ({len(column_headers)} 列)")
            
            # 提取数据
            data_start_row = self.data_start_row.get() - 1  # 转换为0-based索引
            print(data_start_row)
            if data_start_row <= header_row or data_start_row >= len(df):
                messagebox.showerror("错误", f"数据起始行号无效 (必须大于表头行号且小于 {len(df)})")
                return
                
            self.log_message(f"从第 {data_start_row+1} 行开始提取数据")
            
            self.processed_data = []
            for i in range(data_start_row, len(df)):
                row_content = str(df.iloc[i, 0])
                if row_content.strip() and ',' in row_content:
                    row_data = row_content.split(',')
                    chip_data = {}
                    for j, col in enumerate(column_headers):
                        chip_data[col] = row_data[j] if j < len(row_data) else ''
                    self.processed_data.append(chip_data)
            print(column_headers)
            self.log_message(f"成功提取 {len(self.processed_data)} 条数据记录")
            
            
            # 保存为JSON
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(self.processed_data, f, ensure_ascii=False, indent=2)
                
            self.log_message(f"JSON文件已保存至: {output_file}")
            messagebox.showinfo("成功", "数据处理完成")
            
        except Exception as e:
            self.log_message(f"处理过程出错: {str(e)}")
            messagebox.showerror("错误", f"处理过程出错: {str(e)}")
    

if __name__ == "__main__":
    root = tk.Tk()
    app = CSVDataProcessor(root)
    root.mainloop()
